package casia.isiteam.springbootshiro.properties.shiro;


import casia.isiteam.springbootshiro.model.po.common.UserInfo;
import casia.isiteam.springbootshiro.service.user.UserInfoService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * Author wzy
 * Date 2017/7/30 20:22
 */
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 权限认证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) throws AuthenticationException{
        String username = (String) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        UserInfo userInfo = userInfoService.findByUsername(username);
        Set<String> permissions = new HashSet<>();
        Set<String> roles = new HashSet<>();
        if( userInfo != null ){
            roles.add( String.valueOf( userInfo.getRole() ) );
            permissions.add( String.valueOf( userInfo.getSysGrade() ) );
        }

        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
//        authorizationInfo.setObjectPermissions();
        return authorizationInfo;
    }

    /**
     * 登陆认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        String username = (String) authenticationToken.getPrincipal();
        UserInfo user = userInfoService.findByUsername(username);

        if (user == null) {
            throw new UnknownAccountException();
        }else if ( user.getStatus() == 0 ){
            throw new DisabledAccountException();//禁止登陆
        }else if ( user.getDeadline() != null && user.getDeadline().getTime()< System.currentTimeMillis() ){
            throw new LockedAccountException();//已锁定（过期）
        }

        // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，可以自定义实现
        return new SimpleAuthenticationInfo(user, // 用户
                user.getPassword(), // 密码
                ByteSource.Util.bytes(user.getPassword()),
                getName() // realm name
        );
    }
}
